import os
import sys
import time
import pandas as pd
import akshare as ak
from datetime import datetime, timedelta

begin_day = "20180101"

def get_today_date():
    today = datetime.now().strftime("%Y%m%d")
    return today

def get_pass_date(passnum):
    today = datetime.now()
    past_date = (today - timedelta(days=passnum)).strftime("%Y%m%d")
    return past_date


def get_man(stocknum="000100",targetdate="", period="daily", n=5):
    endday = ""
    startday = ""
    passnum = 5
    if (n <= 5):
        passnum = n*4
    elif (n <= 10):
        passnum = n*3
    else:
        passnum = n*2

    if (not targetdate):
        endday = get_today_date()
    else:
        endday = targetdate

    startday = get_pass_date(passnum)
    dftemp = ak.stock_zh_a_hist(stocknum,
                            period=period,
                            start_date=startday,
                            end_date=endday,
                            adjust="")
    dftarget = dftemp.tail(n)
    man = dftarget.iloc[:, 2].mean()
    return round(man,2)

def make_stock_list():
    result = []
    with open('config.ini','r') as fd:
        for line in fd.readlines():
            result.append(str(line).replace('\n','').replace('\r',''))
    return result

def init_tec_data_daily():
    result = make_stock_list()
    fd = open("ma5.txt",'w')
    for r in result:
        ma5 = get_man(stocknum=r,n=5)
        fd.write(r + " " + str(ma5) + "\n")


def init_stock_day_data(stocknum="000100",targetdate="", period="daily"):
    pass

if __name__ == '__main__':
    init_tec_data_daily()
